package com.sense.feel.login.vm

import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import com.sense.feel.login.model.LoginModel
import com.sense.kukoo.biz_login.R
import com.sense.kukoo.common.config.ConfigManager
import com.sense.kukoo.common.config.UserInfoManager
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.utils.AppConfig
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager

/**
 * @Author Lionszhang
 * @Date 2021/2/25 17:33
 * @Name LoginViewModel.java
 * @Instruction LoginActivity VM类
 */
const val ACTION_TO_PHONE_LOGIN = 1
const val ACTION_TO_FACEBOOK_LOGIN = 2
const val ACTION_TO_LINE_LOGIN = 3
const val ACTION_TO_GOOGLE_LOGIN = 4
const val ACTION_TO_ENTER_APP = 5
const val ACTION_TO_CLOSE = 6
const val ACTION_TO_INTEREST_PAGE = 7
const val ACTION_UPDATE_CONFIG_SUCCESS = 8
const val ACTION_SELECT_COUNTRY = 9
const val ACTION_PHONE_LOGIN_TO_PICTURE_VERIFY = 10
const val ACTION_PHONE_LOGIN_GETCODE_SUCCESS = 11
const val ACTION_PHONE_LOGIN_GETCODE_BACK = 12
const val ACTION_PHONE_REGISTER_SUCCESS_TO_INTEREST = 13

// 登陆成功
const val ACTION_PHONE_LOGIN_SUCCESS_TO_HOME = 14

// 验证码回调
const val PICTURE_VERIFY_ACTIVITY_REQUEST_CODE = 15

// 获取验证码失败
const val ACTION_PHONE_LOGIN_GETCODE_FAILED = 16

// 需要帮助
const val ACTION_SHOW_NEED_HELP = 17
const val ACTION_PHONE_LOGIN_FAILED = 18

// 手机号错误
const val ACTION_PHONE_WRONG_NO_FAILED = 19

class LoginViewModel : BaseViewModel() {
    private var mLoginModel: LoginModel? = null
    lateinit var mAreaLiveData: MutableLiveData<String>
    lateinit var mPhoneLiveData: MutableLiveData<String>
    lateinit var mCodeLiveData: MutableLiveData<String>
    private var keyUUID: String? = null

    private var TAG = "LoginViewModel"
    override fun initData() {
        mAreaLiveData = MutableLiveData<String>("886")
        mPhoneLiveData = MutableLiveData<String>()
        mCodeLiveData = MutableLiveData<String>()
    }


    fun doPhoneLogin() {
        toView(ACTION_TO_PHONE_LOGIN)
    }

    fun doGoogleLogin() {
        toView(ACTION_SHOW_DIALOG)
        toView(ACTION_TO_GOOGLE_LOGIN)
    }

    fun doLineLogin() {
        toView(ACTION_SHOW_DIALOG)
        toView(ACTION_TO_LINE_LOGIN)
    }

    fun doFacebookLogin() {
        toView(ACTION_SHOW_DIALOG)
        toView(ACTION_TO_FACEBOOK_LOGIN)
    }

    fun login() {
        toView(ACTION_SHOW_DIALOG)
        toView(ACTION_TO_FACEBOOK_LOGIN)
    }

    fun close() {
        toView(ACTION_TO_CLOSE)
    }

    fun back() {
        toView(ACTION_PHONE_LOGIN_GETCODE_BACK)
    }

    override fun createModel(): BaseMvvmModel? {
        mLoginModel = LoginModel()
        return mLoginModel
    }

    fun startLogin(view: View) {
        val view: TextView = view as TextView
        if (view.text.equals(ApplicationContext.instance().resources?.getString(R.string.login_phone_login_get_verify_code))) {
            val phone = mPhoneLiveData.value
            if (phone.isNullOrEmpty()) {
                sendHintMessage(R.string.login_phone_login_hint)
                return
            }
            toView(ACTION_PHONE_LOGIN_TO_PICTURE_VERIFY)
        } else {
            loginWithPhone()
        }
    }

    fun retry(view: View) {
        val view: TextView = view as TextView
        val str = (ApplicationContext.instance().resources?.getString(R.string.login_reget_code))
        val needHelpStr =
            (ApplicationContext.instance().resources?.getString(R.string.login_need_some_help))
        val viewStr = view.text.toString()
        if (viewStr == str) {
            toView(ACTION_PHONE_LOGIN_TO_PICTURE_VERIFY)
        } else if (viewStr == needHelpStr) {
            toView(ACTION_SHOW_NEED_HELP)
        }
    }

    /**第三方登录*/
    fun login(avatarUrl: String, loginChannelKind: String, nickName: String, userId: String) {
        request {
            val result =
                mLoginModel?.login(avatarUrl, loginChannelKind, nickName, userId)
            if (result?.code == 200) {//上报成功
                var userInfo = result.data
                userInfo?.let {
                    UserInfoManager.instance.saveUserInfo(it)
                }
                getImSig(userInfo?.accessToken)
                if (userInfo?.regOpt == true) {
                    if (loginChannelKind == "Facebook"){
                        //SenseDataAPIUtil.getInstance().reportNewUserNumber("Facebooknewuser_Number")
                    }else if (loginChannelKind == "Line"){
                        //SenseDataAPIUtil.getInstance().reportNewUserNumber("Linenewuser_Number")
                    }else if (loginChannelKind == "Google"){
                        //SenseDataAPIUtil.getInstance().reportNewUserNumber("Googlenewuser_Number")
                    }
                    toView(ACTION_TO_INTEREST_PAGE)

                } else {
                    toView(ACTION_TO_ENTER_APP)
                }
            } else {
                Log.e(TAG, "result0=" + result?.msg)
                result?.msg?.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
            Log.e(TAG, "result1=" + result?.code)
            Log.e(TAG, "result2=" + result?.msg)
        }
    }

    fun getConfigInfo() {
        request(onError = {
            toView(LOAD_ERROR_RETRY)
            Log.i(TAG, "getConfigInfo error a")
        }) {
            val result =
                mLoginModel?.getConfig((if (AppConfig.isDebugKey()) "test" else "prod"), "TW")
            if (result?.code == 200) {//上报成功
                var configInfo = result.data
                configInfo?.let {
                    ConfigManager.instance.saveConfigInfo(it)
                    //todo
                    //HttpClient.instance.setSwitchDomain(true)
                }
                toView(ACTION_UPDATE_CONFIG_SUCCESS)
            } else {
                Log.e(TAG, "result0=" + result?.msg)
                result?.msg?.let { sendHintMessage(it) }
                toView(LOAD_ERROR_RETRY)
            }
            Log.e(TAG, "result1=" + result?.code)
            Log.e(TAG, "result2=" + result?.msg)
        }
    }

    fun getVerifyCode(rand: String, ticket: String) {

        var phone = mPhoneLiveData.value
        val area = mAreaLiveData.value

        if (phone.isNullOrEmpty()) {
            sendHintMessage(R.string.login_phone_login_hint)
            return
        }
        var telPhone = area + phone
        request(
            onError = {
                toView(ACTION_PHONE_LOGIN_GETCODE_FAILED)
            }
        ) {
            val result =
                mLoginModel?.getVerifyCode(telPhone, rand, ticket)
            if (result?.code == 200) {
                sendHintMessage(R.string.login_phone_login_get_verify_code_success)
                keyUUID = result.data
                toView(ACTION_PHONE_LOGIN_GETCODE_SUCCESS)
            } else {
//                result?.msg?.let { sendHintMessage(it) }
                toView(ACTION_PHONE_WRONG_NO_FAILED)
            }

        }
    }

    /**手机号登录*/
    fun loginWithPhone() {
        val phone = mPhoneLiveData.value
        val code = mCodeLiveData.value
        val area = mAreaLiveData.value
        LoggerManager.e(TAG, "phone=" + phone)
        LoggerManager.e(TAG, "code=" + code)
        LoggerManager.e(TAG, "area=" + area)
        if (phone.isNullOrEmpty()) {
            sendHintMessage(R.string.login_phone_login_hint)
            return
        }
        if (code.isNullOrEmpty()) {
            sendHintMessage(R.string.login_phone_login_verify_code_hint)
            return
        }
        var telPhone = area + phone
        toView(ACTION_SHOW_DIALOG)
        request(
            onError = {
                toView(ACTION_PHONE_LOGIN_FAILED)
            }
        ) {
            val result =
                mLoginModel?.login(false, code, telPhone, "", "", keyUUID ?: "")
            if (result?.code == 200) {
                var userInfo = result.data
                userInfo?.let {
                    UserInfoManager.instance.saveUserInfo(it)
                }
                getImSig(userInfo?.accessToken)
                if (userInfo?.regOpt == true) {
                    //SenseDataAPIUtil.getInstance().reportNewUserNumber("Mobilephonenewuser_Number")
                    toView(ACTION_PHONE_REGISTER_SUCCESS_TO_INTEREST)
                } else {
                    toView(ACTION_PHONE_LOGIN_SUCCESS_TO_HOME)
                }
            } else {
                result?.msg?.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    /**获取IM相关配置信息*/
    private suspend fun getImSig(accessToken: String?) {
        val result = mLoginModel?.getImSig(accessToken)
        if (result?.code == 200) {
            val sigInfo = result.data
            var configInfo = ConfigManager.instance.getConfigInfo()
            sigInfo?.let {
                configInfo?.systemUuid = it.systemUuid
                configInfo?.senseUuid = it.senseUuid
                configInfo?.userSig = it.userSig
                ConfigManager.instance.saveConfigInfo(configInfo)
            }
        }
    }

    fun selectCountryArea() {
        toView(ACTION_SELECT_COUNTRY)
    }

    /**
     * @Author Lionszhang
     * @Date 2021/2/25 10:36
     * @Instruction 释放资源
     */
    override fun onCleared() {
        super.onCleared()
        mLoginModel = null
    }
}